//
//  ICMBalanceMaintenanceAndPartsView.m
//  ICrEAM
//
//  Created by Cty on 2016/11/03.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "ICMBalanceMaintenanceAndPartsView.h"
#import "ICMGetCarRepairPartsTableViewCell.h"
#import "ICMGetCarRepairEventTableViewCell.h"
#import "ICMRepairMaintenanceModel.h"
#import "ICMRepairPartsModel.h"
#import "ICMTitleTextFeildView.h"
#import "ICMBalanceRepairEventTableViewCell.h"
#import "ICMBalanceRepairPartsTableViewCell.h"


#define xInset                      ActualWidth(20)
#define xDistance                   ActualWidth(25)
#define yDistance                   ActualHeight(10)
#define TitleTFViewHeight           ActualHeight(63)

@interface ICMBalanceMaintenanceAndPartsView ()<UITableViewDelegate, UITableViewDataSource,UITextFieldDelegate,ICMGetCarRepairEventTableViewCellDelegate,ICMGetCarRepairPartsTableViewCellDelegate,ICMRepairEventAndPartSearchViewControllerDelegate,ICMTitleTextFeildViewDelegate,ICMLevelViewDelegate>



@end

@implementation ICMBalanceMaintenanceAndPartsView


- (ICMRepairEventAndPartSearchViewController *)reapsvc{
    if (!_reapsvc) {
        _reapsvc = [[ICMRepairEventAndPartSearchViewController alloc] init];
        _reapsvc.delegate = self;
    }
    return _reapsvc;
}

- (NSMutableArray *)repairTypes{
    if (!_repairTypes) {
        _repairTypes = [NSMutableArray array];
    }
    return _repairTypes;
}

- (NSMutableArray *)repairEventArray{
    if (!_repairEventArray) {
        _repairEventArray = [NSMutableArray array];
    }
    return _repairEventArray;
}

- (NSMutableArray *)repairPartsArray{
    if (!_repairPartsArray) {
        _repairPartsArray = [NSMutableArray array];
    }
    return _repairPartsArray;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self){
        TPKeyboardAvoidingScrollView *backgroundScrollView = [[TPKeyboardAvoidingScrollView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        backgroundScrollView.backgroundColor = [UIColor clearColor];
        backgroundScrollView.showsVerticalScrollIndicator = NO;
        backgroundScrollView.bounces = NO;
        backgroundScrollView.contentSize = CGSizeMake(frame.size.width, frame.size.height);
        [self addSubview:backgroundScrollView];
        self.backgroundScrollView = backgroundScrollView;
        self.isFirstInsurance = NO;
        self.tureVauleLabourDis = @"1.00";
        self.tureVaulePartDis = @"1.00";
        [self setupTableView];
        [self setupAllPriceView];
        self.backgroundColor = BackgroundColor_White;
    }
    return self;
}

- (void)setupAllPriceView{
    UIView *priceView = [[UIView alloc]initWithFrame:CGRectMake(0, self.repairPartsTableView.bottomEdge, ScreenWidth, ActualHeight(180))];
    [self.backgroundScrollView addSubview:priceView];
    //第一行
    ICMTitleTextFeildView *workingUnitPriceView = [ICMTitleTextFeildView createNoneditableICMTitleTextFeildViewWithFrame:CGRectMake(xInset, yDistance, ActualWidth(220), TitleTFViewHeight) title:@"工时单价"];
    workingUnitPriceView.contentText = @"50.00";
    [priceView addSubview:workingUnitPriceView];
    
    ICMTitleTextFeildView *workingPriceView = [ICMTitleTextFeildView createNoneditableICMTitleTextFeildViewWithFrame:CGRectMake(workingUnitPriceView.rightEdge+xDistance, workingUnitPriceView.y, ActualWidth(220), TitleTFViewHeight) title:@"工时费"];
    workingPriceView.contentText = @"0.00";
    workingPriceView.contentTextFeild.keyboardType = UIKeyboardTypeDecimalPad;
    workingPriceView.contentTextFeild.delegate = self;
    [priceView addSubview:workingPriceView];
    
    ICMTitleTextFeildView *partsPriceView = [ICMTitleTextFeildView createNoneditableICMTitleTextFeildViewWithFrame:CGRectMake(workingPriceView.rightEdge+xDistance, workingPriceView.y, ActualWidth(220), TitleTFViewHeight) title:@"零件费"];
    partsPriceView.contentText = @"0.00";
    partsPriceView.contentTextFeild.keyboardType = UIKeyboardTypeNumberPad;
    partsPriceView.contentTextFeild.delegate = self;
    [priceView addSubview:partsPriceView];
    
    ICMTitleTextFeildView *totalPriceView = [ICMTitleTextFeildView createNoneditableICMTitleTextFeildViewWithFrame:CGRectMake(partsPriceView.rightEdge+xDistance, partsPriceView.y, ActualWidth(220), TitleTFViewHeight) title:@"折前总金额"];
    totalPriceView.contentText = @"0.00";
    totalPriceView.contentTextFeild.keyboardType = UIKeyboardTypeDecimalPad;
    totalPriceView.contentTextFeild.delegate = self;
    [priceView addSubview:totalPriceView];
    
    self.workingUnitPriceView = workingUnitPriceView;
    self.workingPriceView = workingPriceView;
    self.partsPriceView = partsPriceView;
    self.totalPriceView = totalPriceView;
    
    //第二行
    
    ICMTitleTextFeildView *discountModeView = [ICMTitleTextFeildView createClickableICMTitleTextFeildViewWithFrame:CGRectMake(xInset, workingUnitPriceView.bottomEdge+yDistance, ActualWidth(220), TitleTFViewHeight) title:@"优惠模式" addTarget:nil selector:nil];
    discountModeView.delegate = self;
    [priceView addSubview:discountModeView];
    
    ICMTitleTextFeildView *workingRatioView = [ICMTitleTextFeildView createEditableICMTitleTextFeildViewWithFrame:CGRectMake(discountModeView.rightEdge+xDistance, workingPriceView.bottomEdge+yDistance, ActualWidth(220), TitleTFViewHeight) title:@"工时折扣率"];
    workingRatioView.contentText = @"1.00";
    workingRatioView.delegate = self;
    workingRatioView.contentTextFeild.keyboardType = UIKeyboardTypeNumberPad;
    workingRatioView.contentTextFeild.delegate = self;
    [priceView addSubview:workingRatioView];
    
    ICMTitleTextFeildView *partsRatioView = [ICMTitleTextFeildView createEditableICMTitleTextFeildViewWithFrame:CGRectMake(workingRatioView.rightEdge+xDistance, workingRatioView.y, ActualWidth(220), TitleTFViewHeight) title:@"零件折扣率"];
    partsRatioView.contentText = @"1.00";
    partsRatioView.delegate = self;
    partsRatioView.contentTextFeild.keyboardType = UIKeyboardTypeNumberPad;
    partsRatioView.contentTextFeild.delegate = self;
    [priceView addSubview:partsRatioView];
    
    ICMTitleTextFeildView *discountedPrice = [ICMTitleTextFeildView createNoneditableICMTitleTextFeildViewWithFrame:CGRectMake(partsRatioView.rightEdge+xDistance, partsRatioView.y, ActualWidth(220), TitleTFViewHeight) title:@"折后总金额"];
    discountedPrice.contentText = @"0.00";
    discountedPrice.contentTextFeild.keyboardType = UIKeyboardTypeDecimalPad;
    discountedPrice.contentTextFeild.delegate = self;
    [priceView addSubview:discountedPrice];
    
    self.firstInsuranceeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, discountedPrice.bottomEdge+ActualHeight(20), ScreenWidth, ActualHeight(30))];
    self.firstInsuranceeLabel.text = @"首保结算时，请注意配件补差！";
    self.firstInsuranceeLabel.textColor = [UIColor redColor];
    self.firstInsuranceeLabel.font = NaviFont;
    self.firstInsuranceeLabel.textAlignment = NSTextAlignmentCenter;
    [priceView addSubview:self.firstInsuranceeLabel];
    self.firstInsuranceeLabel.hidden = YES;
    
    self.discountModeView = discountModeView;
    self.workingRatioView = workingRatioView;
    self.partsRatioView = partsRatioView;
    self.discountedPrice = discountedPrice;
    
}

#pragma mark -- 获取优惠模式折扣力度
- (void)getDiscountModeData:(NSString *)ownerCode WithPS:(NSString *)ps WithType:(int)type
{
    if ([self.delegate respondsToSelector:@selector(getMaintenanceAndPartsDiscountModeData:WithPS:WithType:)]) {
        [self.delegate getMaintenanceAndPartsDiscountModeData:ownerCode WithPS:ps WithType:type];
    }
}

- (void)setupTableView {
    [self setupRepairEventHeaderView];
    
    UITableView *repairEventTableView = [[UITableView alloc] initWithFrame:CGRectMake(xInset, yDistance+ActualHeight(25), ScreenWidth-xInset*2, ActualHeight(125))];
    self.repairEventTableView = repairEventTableView;
    repairEventTableView.delegate = self;
    repairEventTableView.dataSource = self;
    repairEventTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [repairEventTableView registerClass:[ICMBalanceRepairEventTableViewCell class] forCellReuseIdentifier:@"repairEventCell"];
    repairEventTableView.backgroundColor = [UIColor clearColor];
    repairEventTableView.tableFooterView = [[UIView alloc] init];
    [self.backgroundScrollView addSubview:repairEventTableView];
    
    [self setupRepairPartsHeaderView];
    
    UITableView *repairPartsTableView = [[UITableView alloc] initWithFrame:CGRectMake(xInset, ActualHeight(180), ScreenWidth-xInset*2, ActualHeight(125))];
    self.repairPartsTableView = repairPartsTableView;
    repairPartsTableView.delegate = self;
    repairPartsTableView.dataSource = self;
    repairPartsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [repairPartsTableView registerClass:[ICMBalanceRepairPartsTableViewCell class] forCellReuseIdentifier:@"repairPartsCell"];
    repairPartsTableView.backgroundColor = [UIColor clearColor];
    repairPartsTableView.tableFooterView = [[UIView alloc] init];
    [self.backgroundScrollView addSubview:repairPartsTableView];
}

- (void)setupRepairEventHeaderView{
    UIView *repairEventHeadView = [[UIView alloc] initWithFrame:CGRectMake(xInset, yDistance, ScreenWidth-xInset*2, ActualHeight(25))];
    repairEventHeadView.backgroundColor = TitleColor;
    
    
    UILabel *orderLabel = [self createLabelWithText:@"序号" frame:CGRectMake(0, ActualHeight(5), ActualWidth(60), ActualHeight(15))];
    [repairEventHeadView addSubview:orderLabel];
    
    UIView *secondSep = [[UIView alloc] initWithFrame:CGRectMake(orderLabel.rightEdge, 0, 1, repairEventHeadView.height)];
    secondSep.backgroundColor = BorderColor_Gray;
    [repairEventHeadView addSubview:secondSep];
    
    UILabel *eventNumberLabel = [self createLabelWithText:@"项目代码" frame:CGRectMake(secondSep.rightEdge, orderLabel.y, ActualWidth(145), ActualHeight(15))];
    [repairEventHeadView addSubview:eventNumberLabel];
    
    UIView *thirdSep = [[UIView alloc] initWithFrame:CGRectMake(eventNumberLabel.rightEdge, 0, 1, repairEventHeadView.height)];
    thirdSep.backgroundColor = BorderColor_Gray;
    [repairEventHeadView addSubview:thirdSep];
    
    UILabel *eventNameLabel = [self createLabelWithText:@"项目名称" frame:CGRectMake(thirdSep.rightEdge, orderLabel.y, ActualWidth(245), ActualHeight(15))];
    [repairEventHeadView addSubview:eventNameLabel];
    
    UIView *fourthSep = [[UIView alloc] initWithFrame:CGRectMake(eventNameLabel.rightEdge, 0, 1, repairEventHeadView.height)];
    fourthSep.backgroundColor = BorderColor_Gray;
    [repairEventHeadView addSubview:fourthSep];
    
    UILabel *workingTimeLabel = [self createLabelWithText:@"执行工时" frame:CGRectMake(fourthSep.rightEdge, orderLabel.y, ActualWidth(75), ActualHeight(15))];
    [repairEventHeadView addSubview:workingTimeLabel];
    
    UIView *fifthSep = [[UIView alloc] initWithFrame:CGRectMake(workingTimeLabel.rightEdge, 0, 1, repairEventHeadView.height)];
    fifthSep.backgroundColor = BorderColor_Gray;
    [repairEventHeadView addSubview:fifthSep];
    
    UILabel *priceLabel = [self createLabelWithText:@"工时单价" frame:CGRectMake(fifthSep.rightEdge, orderLabel.y, ActualWidth(75), ActualHeight(15))];
    [repairEventHeadView addSubview:priceLabel];
    
    UIView *priceSep = [[UIView alloc] initWithFrame:CGRectMake(priceLabel.rightEdge, 0, 1, repairEventHeadView.height)];
    priceSep.backgroundColor = BorderColor_Gray;
    [repairEventHeadView addSubview:priceSep];
    
    UILabel *workingPriceLabel = [self createLabelWithText:@"工时费" frame:CGRectMake(priceLabel.rightEdge, orderLabel.y, ActualWidth(76), ActualHeight(15))];
    [repairEventHeadView addSubview:workingPriceLabel];
    
    UIView *sixthSep = [[UIView alloc] initWithFrame:CGRectMake(workingPriceLabel.rightEdge, 0, 1, repairEventHeadView.height)];
    sixthSep.backgroundColor = BorderColor_Gray;
    [repairEventHeadView addSubview:sixthSep];
    
    UILabel *repairTypeLabel = [self createLabelWithText:@"维修类型" frame:CGRectMake(sixthSep.rightEdge, orderLabel.y, ActualWidth(85), ActualHeight(15))];
    [repairEventHeadView addSubview:repairTypeLabel];
    
    UIView *seventhSep = [[UIView alloc] initWithFrame:CGRectMake(repairTypeLabel.rightEdge, 0, 1, repairEventHeadView.height)];
    seventhSep.backgroundColor = BorderColor_Gray;
    [repairEventHeadView addSubview:seventhSep];
    
    UILabel *breakdownDiscribeLabel = [self createLabelWithText:@"故障描述" frame:CGRectMake(seventhSep.rightEdge, orderLabel.y, repairEventHeadView.width-repairTypeLabel.rightEdge, ActualHeight(15))];
    [repairEventHeadView addSubview:breakdownDiscribeLabel];
    
    [self.backgroundScrollView addSubview:repairEventHeadView];
}

- (void)setupRepairPartsHeaderView{
    UIView *repairPartsHeadView = [[UIView alloc] initWithFrame:CGRectMake(xInset, ActualHeight(155), ScreenWidth-xInset*2, ActualHeight(25))];
    repairPartsHeadView.backgroundColor = TitleColor;
    
    
    UILabel *orderLabel = [self createLabelWithText:@"序号" frame:CGRectMake(0, ActualHeight(5), ActualWidth(60), ActualHeight(15))];
    [repairPartsHeadView addSubview:orderLabel];
    
    UIView *secondSep = [[UIView alloc] initWithFrame:CGRectMake(orderLabel.rightEdge, 0, 1, repairPartsHeadView.height)];
    secondSep.backgroundColor = BorderColor_Gray;
    [repairPartsHeadView addSubview:secondSep];
    
    UILabel *partNumberLabel = [self createLabelWithText:@"零件代码" frame:CGRectMake(secondSep.rightEdge, orderLabel.y, ActualWidth(145), ActualHeight(15))];
    [repairPartsHeadView addSubview:partNumberLabel];
    
    UIView *thirdSep = [[UIView alloc] initWithFrame:CGRectMake(partNumberLabel.rightEdge, 0, 1, repairPartsHeadView.height)];
    thirdSep.backgroundColor = BorderColor_Gray;
    [repairPartsHeadView addSubview:thirdSep];
    
    UILabel *partNameLabel = [self createLabelWithText:@"零件名称" frame:CGRectMake(thirdSep.rightEdge, orderLabel.y, ActualWidth(245), ActualHeight(15))];
    [repairPartsHeadView addSubview:partNameLabel];
    
    UIView *fourthSep = [[UIView alloc] initWithFrame:CGRectMake(partNameLabel.rightEdge, 0, 1, repairPartsHeadView.height)];
    fourthSep.backgroundColor = BorderColor_Gray;
    [repairPartsHeadView addSubview:fourthSep];
    
    UILabel *numberLabel = [self createLabelWithText:@"数量" frame:CGRectMake(fourthSep.rightEdge, orderLabel.y, ActualWidth(75), ActualHeight(15))];
    [repairPartsHeadView addSubview:numberLabel];
    
    UIView *fifthSep = [[UIView alloc] initWithFrame:CGRectMake(numberLabel.rightEdge, 0, 1, repairPartsHeadView.height)];
    fifthSep.backgroundColor = BorderColor_Gray;
    [repairPartsHeadView addSubview:fifthSep];
    
    UILabel *unitPriceLabel = [self createLabelWithText:@"单价" frame:CGRectMake(fifthSep.rightEdge, orderLabel.y, ActualWidth(75), ActualHeight(15))];
    [repairPartsHeadView addSubview:unitPriceLabel];
    
    UIView *sixthSep = [[UIView alloc] initWithFrame:CGRectMake(unitPriceLabel.rightEdge, 0, 1, repairPartsHeadView.height)];
    sixthSep.backgroundColor = BorderColor_Gray;
    [repairPartsHeadView addSubview:sixthSep];
    
    UILabel *totalPriceLabel = [self createLabelWithText:@"销售金额" frame:CGRectMake(sixthSep.rightEdge, orderLabel.y, ActualWidth(75), ActualHeight(15))];
    [repairPartsHeadView addSubview:totalPriceLabel];
    
    UIView *seventhSep = [[UIView alloc] initWithFrame:CGRectMake(totalPriceLabel.rightEdge, 0, 1, repairPartsHeadView.height)];
    seventhSep.backgroundColor = BorderColor_Gray;
    [repairPartsHeadView addSubview:seventhSep];
    
    UILabel *repairTypeLabel = [self createLabelWithText:@"维修类型" frame:CGRectMake(seventhSep.rightEdge, orderLabel.y, ActualWidth(85), ActualHeight(15))];
    [repairPartsHeadView addSubview:repairTypeLabel];
    
    UIView *eighthSep = [[UIView alloc] initWithFrame:CGRectMake(repairTypeLabel.rightEdge, 0, 1, repairPartsHeadView.height)];
    eighthSep.backgroundColor = BorderColor_Gray;
    [repairPartsHeadView addSubview:eighthSep];
    
    UILabel *stockPlaceLabel = [self createLabelWithText:@"库位代码" frame:CGRectMake(eighthSep.rightEdge, orderLabel.y, ActualWidth(125), ActualHeight(15))];
    [repairPartsHeadView addSubview:stockPlaceLabel];
    
    UIView *ninthSep = [[UIView alloc] initWithFrame:CGRectMake(stockPlaceLabel.rightEdge, 0, 1, repairPartsHeadView.height)];
    ninthSep.backgroundColor = BorderColor_Gray;
    [repairPartsHeadView addSubview:ninthSep];
    
    UILabel *partPropertyLabel = [self createLabelWithText:@"零件属性" frame:CGRectMake(ninthSep.rightEdge, orderLabel.y, repairPartsHeadView.width-stockPlaceLabel.rightEdge, ActualHeight(15))];
    [repairPartsHeadView addSubview:partPropertyLabel];
    
    [self.backgroundScrollView addSubview:repairPartsHeadView];
}

#pragma tableViewDelegateAndDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.repairEventTableView) {
        return self.repairEventArray.count;
    } else if (tableView == self.repairPartsTableView) {
        return self.repairPartsArray.count;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return ActualHeight(25.0);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.repairEventTableView) {
        ICMBalanceRepairEventTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"repairEventCell"];
        if (!cell) {
            cell = [[ICMBalanceRepairEventTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"repairEventCell"];
        }
        cell.order = indexPath.row;
        if (self.repairEventArray.count > indexPath.row) {
            [cell setupLabelsWithModel:self.repairEventArray[indexPath.row]];
            if (self.isFirstInsurance && indexPath.row == 0) {
                if (self.workingPrice && self.workingTime) {
                    [cell setupWorkingTime:self.workingTime workingPrice:self.workingPrice];
                }
            }
        }
        return cell;
    } else if (tableView == self.repairPartsTableView) {
        ICMBalanceRepairPartsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"repairPartsCell"];
        if (!cell) {
            cell = [[ICMBalanceRepairPartsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"repairPartsCell"];
        }
        cell.order = indexPath.row;
        if (self.repairPartsArray.count > indexPath.row) {
            [cell setupLabelsWithModel:self.repairPartsArray[indexPath.row]];
        }
        return cell;
    }
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    return cell;
}


#pragma mark -- 判断折扣权限
- (void)textFieldDidEndEditing:(UITextField *)textField{
    float number = [textField.text floatValue];
    textField.text = [NSString stringWithFormat:@"%.2f", number];
    if (textField == self.workingRatioView.contentTextFeild
        ||
        textField == self.partsRatioView.contentTextFeild) {
        if ([textField.text integerValue] >= 1) {
            textField.text = @"1.00";
        }
        //判断是否有权限
        if(textField == self.workingRatioView.contentTextFeild)
        {
            if(self.myLabourDisLimit > [self.workingRatioView.contentText doubleValue] && self.otherLabourDisLimit > [self.workingRatioView.contentText doubleValue] && ![textField.text isEqualToString:@""])
            {
                //授权
                [Window addSubview:self.blankView];
                [Window addSubview:self.levelView];
                return;
            }
        }
        if(textField == self.partsRatioView.contentTextFeild)
        {
            if(self.myPartDisLimit > [self.partsRatioView.contentText doubleValue] && self.otherPartDisLimit > [self.partsRatioView.contentText doubleValue] && ![textField.text isEqualToString:@""])
            {
                //授权
                [Window addSubview:self.blankView];
                [Window addSubview:self.levelView];
                return;
            }
        }
        
        [self calculateRatioPrice];
        
        if(textField == self.workingRatioView.contentTextFeild)
        {
            self.tureVauleLabourDis = self.workingRatioView.contentTextFeild.text;
        }
        if(textField == self.partsRatioView.contentTextFeild)
        {
            self.tureVaulePartDis = self.partsRatioView.contentTextFeild.text;
        }
    }
}

#pragma mark -- 计算折扣
- (void)calculateRatioPrice{
    double ratioEventPrice = 0.00;//折后工时费
    double ratioPartPrice = 0.00;//折后材料费
    
    for (ICMRepairMaintenanceModel *model in self.repairEventArray) {
        if (model.isDiscount) {
            model.DISCOUNT = [self.workingRatioView.contentText doubleValue];
        }
    }
    
    for (ICMRepairPartsModel *model in self.repairPartsArray) {
        if (model.isDiscount) {
            model.DISCOUNT = [self.partsRatioView.contentText doubleValue];
        }
    }
    
    
    for (ICMRepairMaintenanceModel *model in self.repairEventArray)
    {
        if (model.isDiscount)
        {
            ratioEventPrice = ratioEventPrice + [model.LABOUR_AMOUNT doubleValue] * model.DISCOUNT;
            ratioEventPrice = [[NSString stringWithFormat:@"%.2f",ratioEventPrice] doubleValue];
        }
        else
        {
            ratioEventPrice += [model.LABOUR_AMOUNT doubleValue];
            ratioEventPrice = [[NSString stringWithFormat:@"%.2f",ratioEventPrice] doubleValue];
        }
    }
    
    for (ICMRepairPartsModel *model in self.repairPartsArray)
    {
        if (model.isDiscount)
        {
            ratioPartPrice += [model.PART_SALES_AMOUNT doubleValue] * model.DISCOUNT;
            ratioPartPrice = [[NSString stringWithFormat:@"%.2f",ratioPartPrice] doubleValue];
        }
        else
        {
            ratioPartPrice += [model.PART_SALES_AMOUNT doubleValue];
            ratioPartPrice = [[NSString stringWithFormat:@"%.2f",ratioPartPrice] doubleValue];
        }
        
    }
    
    self.discountedPrice.contentText = [NSString stringWithFormat:@"%.2f", ratioEventPrice+ratioPartPrice];
    NSString *ratioEventPriceStr = [NSString stringWithFormat:@"%.2f", ratioEventPrice];
    NSString *ratioPartPriceStr = [NSString stringWithFormat:@"%.2f", ratioPartPrice];
    if (self.isFirstInsurance) {
        self.discountedPrice.contentText = self.totalPriceView.contentText;
        ratioEventPriceStr = self.workingPriceView.contentText;
    }
    //发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"CalculateRatioPrice" object:self userInfo:@{@"ratioEventPrice":ratioEventPriceStr,@"ratioPartPrice":ratioPartPriceStr,@"DiscountedPrice":self.discountedPrice.contentText,@"workingPrice":self.workingPriceView.contentText,@"partsPrice":self.partsPriceView.contentText,@"totalPrice":self.totalPriceView.contentText}];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    BOOL isHavePoint = YES;
    if ([textField.text rangeOfString:@"."].location == NSNotFound) {
        isHavePoint = NO;
    }
    if ([string length]>0)
    {
        unichar single = [string characterAtIndex:0];//当前输入的字符
        if ((single >= '0' && single <= '9') || single == '.')//数据格式正确
        {
            //首字母不能为0和小数点
            if([textField.text length] == 0){
                if(single == '.'){
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            }
            if (single == '.')
            {
                if(!isHavePoint)//text中还没有小数点
                {
                    isHavePoint=YES;
                    return YES;
                }else
                {
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            }
            else
            {
                if (isHavePoint)//存在小数点
                {
                    //判断小数点的位数
                    NSRange ran = [textField.text rangeOfString:@"."];
                    int tt = range.location-ran.location;
                    if (tt <= 2){
                        return YES;
                    } else {
                        return NO;
                    }
                } else {
                    return YES;
                }
            }
        } else {//输入的数据格式不正确
            [textField.text stringByReplacingCharactersInRange:range withString:@""];
            return NO;
        }
    } else {
        return YES;
    }
    return YES;
}


- (UILabel *)createLabelWithText:(NSString *)text frame:(CGRect)frame{
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.text = text;
    label.font = TitleFont;
    label.textColor = ContentTextColor_Black;
    label.textAlignment = NSTextAlignmentCenter;
    return label;
}

+ (instancetype)createICMMaintenanceAndPartsViewWithFrame:(CGRect)frame{
    return [[ICMBalanceMaintenanceAndPartsView alloc] initWithFrame:frame];
}

#pragma mark --设置页面

- (void)setupPartsViewWithBasicModel:(ICMBalanceBasicInfoModel *)basicModel{
    if ([basicModel.RO_REPAIR_TYPE_NAME isEqualToString:@"质量担保保养"]) {
        self.firstInsuranceeLabel.hidden = NO;
        self.isFirstInsurance = YES;
        self.SB_PRICE = basicModel.SB_PRICE?:@"0";
        self.discountModeView.borderView.backgroundColor = TextFeildBackgroundColor_Gray;
        self.discountModeView.userInteractionEnabled = NO;
        self.workingRatioView.borderView.backgroundColor = TextFeildBackgroundColor_Gray;
        self.workingRatioView.userInteractionEnabled = NO;
        self.partsRatioView.borderView.backgroundColor = TextFeildBackgroundColor_Gray;
        self.partsRatioView.userInteractionEnabled = NO;
    }else{
        self.workingPriceView.contentText = basicModel.LABOUR_AMOUNT;//折前工时费
        self.partsPriceView.contentText = basicModel.REPAIR_PART_AMOUNT;//折前材料费
        self.totalPriceView.contentText = basicModel.REPAIR_AMOUNT;//折前总金额
    }
    
    self.workingUnitPriceView.contentText = basicModel.LABOUR_PRICE;//工时单价
    //    self.workingRatioView.contentText = basicModel.LABOUR_RATE;//工时折扣率
    //    self.partsRatioView.contentText = basicModel.PART_RATE;//零件折扣率
    self.discountedPrice.contentText = basicModel.REAL_TOTAL_AMOUNT;//折后总金额
    //获取自己的折扣权限
    [self getDiscountModeData:[ICrEAMUser shareICrEAMUser].employee_NO WithPS:[ICrEAMUser shareICrEAMUser].passWord WithType:0];
    self.levelNo = [ICrEAMUser shareICrEAMUser].employee_NO;
    
}
- (void)setupPartsViewWithRepairMaintenancesModel:(ICMRepairMaintenancesModel*)repairMaintenancesModel{
    self.repairEventArray = repairMaintenancesModel.TT_RO_LABOUR;
    if (self.isFirstInsurance) {
        double ratioEventPrice = 0.00;
        for (ICMRepairMaintenanceModel *model in self.repairEventArray)
        {
            model.DISCOUNT = 1.0;
            if ([self.repairEventArray indexOfObject:model] == 0 && self.isFirstInsurance) {
                ratioEventPrice += [self.workingPrice doubleValue];
                ratioEventPrice = [[NSString stringWithFormat:@"%.2f",ratioEventPrice] doubleValue];
            }else{
                ratioEventPrice += [model.LABOUR_AMOUNT doubleValue];
                ratioEventPrice = [[NSString stringWithFormat:@"%.2f",ratioEventPrice] doubleValue];
            }
        }
        NSString *workingPrice = [NSString stringWithFormat:@"%.2f",ratioEventPrice];
        self.workingPriceView.contentText = [NSString stringWithFormat:@"%.2f",[workingPrice doubleValue]];//折前工时费
        self.totalPriceView.contentText = [NSString stringWithFormat:@"%.2f",([self.workingPriceView.contentText doubleValue] + [self.partsPriceView.contentText doubleValue])];//折前总金额
        self.discountedPrice.contentText = [NSString stringWithFormat:@"%.2f",([self.workingPriceView.contentText doubleValue] + [self.partsPriceView.contentText doubleValue])];//折后总金额
    }else{
        //非首保
        double ratioEventPrice = 0.00;
        for (ICMRepairMaintenanceModel *model in self.repairEventArray)
        {
            model.DISCOUNT = 1.0;
            ratioEventPrice += [model.LABOUR_AMOUNT doubleValue];
            ratioEventPrice = [[NSString stringWithFormat:@"%.2f",ratioEventPrice] doubleValue];
        }
        self.workingPriceView.contentText = [NSString stringWithFormat:@"%.2f",ratioEventPrice];//折前工时费
        self.totalPriceView.contentText = [NSString stringWithFormat:@"%.2f",([self.workingPriceView.contentText doubleValue] + [self.partsPriceView.contentText doubleValue])];//折前总金额
    }
    [self calculateRatioPrice];
    [self.repairEventTableView reloadData];
}
- (void)setupPartsViewWithRepairPartsArrayModel:(ICMRepairPartsArrayModel*)repairPartsArrayModel{
    self.repairPartsArray = repairPartsArrayModel.TT_RO_REPAIR_PART;
    double ratioPartPrice = 0.00;
    for (ICMRepairPartsModel *model in self.repairPartsArray)
    {
        model.DISCOUNT = 1.0;
        ratioPartPrice += [model.PART_SALES_AMOUNT doubleValue];
        ratioPartPrice = [[NSString stringWithFormat:@"%.2f",ratioPartPrice] doubleValue];
    }
    if (self.isFirstInsurance) {
        self.partsPriceView.contentText = [NSString stringWithFormat:@"%.2f",ratioPartPrice];//折前材料费
        self.workingTime = [NSString stringWithFormat:@"%.2f",([self.SB_PRICE doubleValue] - ratioPartPrice)/ [self.workingUnitPriceView.contentText doubleValue]];
        self.workingPrice = [NSString stringWithFormat:@"%.2f",[self.SB_PRICE doubleValue] - ratioPartPrice];
    }else{
        self.partsPriceView.contentText = [NSString stringWithFormat:@"%.2f",ratioPartPrice];//折前材料费
    }
    
    [self.repairPartsTableView reloadData];
}

- (void)refreshInEditType{
    [self.repairEventTableView reloadData];
    [self.repairPartsTableView reloadData];
}

//ICMTitleTextFeildViewDelegate
#pragma mark -- 优惠模式回调
- (void)clickedData:(ICMTitleTextFeildView *)titleTextFeildView
{
    if(titleTextFeildView == self.discountModeView)
    {
        double labour = [self.firstArray[self.discountModeView.selectIndex][@"LABOUR_AMOUNT_DISCOUNT"] doubleValue];
        double part = [self.firstArray[self.discountModeView.selectIndex][@"REPAIR_PART_DISCOUNT"] doubleValue];
        if(labour < 1)
        {
            self.workingRatioView.contentText = [NSString stringWithFormat:@"%f",labour];
        }
        else
        {
            self.workingRatioView.contentText = @"1.00";
        }
        if(part < 1)
        {
            self.partsRatioView.contentText = [NSString stringWithFormat:@"%f",part];
            
        }
        else
        {
            self.partsRatioView.contentText = @"1.00";
        }
        self.tureVauleLabourDis = self.workingRatioView.contentText;
        self.tureVaulePartDis = self.partsRatioView.contentText;
        //重新计算
        for (ICMRepairMaintenanceModel *model in self.repairEventArray) {
            if (model.isDiscount) {
                model.DISCOUNT = [self.workingRatioView.contentText doubleValue];
            }
        }
        
        for (ICMRepairPartsModel *model in self.repairPartsArray) {
            if (model.isDiscount) {
                model.DISCOUNT = [self.partsRatioView.contentText doubleValue];
            }
        }
        [self calculateRatioPrice];
        
    }
    
}

- (NSMutableArray *)disArray
{
    if(!_disArray)
    {
        _disArray = [[NSMutableArray alloc] init];
    }
    return _disArray;
}

- (ICMLevelView *)levelView
{
    if(!_levelView)
    {
        _levelView = [[ICMLevelView alloc] initWithFrame:CGRectMake((Window.bounds.size.width-300)/2, (Window.bounds.size.height-320)/2, 300, 320)];
    }
    _levelView.delegate = self;
    return _levelView;
}

- (UIView *)blankView{
    if (!_blankView) {
        _blankView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _blankView.backgroundColor = [UIColor clearColor];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideBlankView)];
        [_blankView addGestureRecognizer:tap];
    }
    return _blankView;
}

- (void)hideBlankView{
    [self.levelView removeFromSuperview];
    [self.blankView removeFromSuperview];
}

#pragma mark -- 折扣授权页面
//ICMLevelViewDelegate
- (void)levelCommitWithName:(NSString *)name WithPs:(NSString *)ps
{
    [self hideBlankView];
    [self.levelView removeFromSuperview];
    [self getDiscountModeData:name WithPS:ps WithType:1];
}
- (void)levelCancel
{
    [self hideBlankView];
    self.workingRatioView.contentTextFeild.text = self.tureVauleLabourDis;
    self.partsRatioView.contentTextFeild.text = self.tureVaulePartDis;
    [self.levelView removeFromSuperview];
}

#pragma 页面值变化
//值变化调用此方法
- (void)iCMTitleTextFeildViewValueChanged
{
    self.hasViewValueChanged = YES;
}

//值变化调用此方法
- (void)iCMTitleTextViewValueChanged
{
    self.hasViewValueChanged = YES;
}

- (void)setHasViewValueChanged:(BOOL)hasViewValueChanged
{
    _hasViewValueChanged = hasViewValueChanged;
    if(_hasViewValueChanged)
    {
        //发送变化通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"BalanceViewValueChanged" object:self];
    }
}




@end

